﻿using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Spark.Core.Exceptions;
using System;

namespace Spark.Logging.Extensions
{
    public static class ApplicationBuilderExtensions
    {
        /// <summary>
        /// 添加日志
        /// </summary>
        /// <returns></returns>
        public static IApplicationBuilder UseSparkLog(this IApplicationBuilder app)
        {
            var factory = app.ApplicationServices.GetRequiredService<ILoggerFactory>();
            var logStore = app.ApplicationServices.GetRequiredService<ILogStore>();
            var httpContextAccessor = app.ApplicationServices.GetRequiredService<IHttpContextAccessor>();

            string appName = Environment.GetEnvironmentVariable("AppCode");
            if (string.IsNullOrWhiteSpace(appName))
                throw new SparkException("请注入环境变量AppCode！");

            string serviceName = Environment.GetEnvironmentVariable("ServiceName");
            if (string.IsNullOrWhiteSpace(serviceName))
                serviceName = appName;

            var provider = new SparkLogProvider(logStore, httpContextAccessor, new SparkLoggerProperties(appName, serviceName));
            factory.AddProvider(provider);

            return app;
        }

        /// <summary>
        /// 添加日志
        /// </summary>
        /// <returns></returns>
        public static IApplicationBuilder UseSparkLog(this IApplicationBuilder app, Action<SparkLoggerProperties> action)
        {
            if (action == null)
                throw new ArgumentNullException(nameof(action));

            var factory = app.ApplicationServices.GetRequiredService<ILoggerFactory>();
            var logStore = app.ApplicationServices.GetRequiredService<ILogStore>();
            var httpContextAccessor = app.ApplicationServices.GetRequiredService<IHttpContextAccessor>();

            var loggerProperties = new SparkLoggerProperties();
            action?.Invoke(loggerProperties);

            if (string.IsNullOrWhiteSpace(loggerProperties.AppCode))
                throw new ArgumentNullException(nameof(loggerProperties.AppCode));

            if (string.IsNullOrWhiteSpace(loggerProperties.ServiceName))
                loggerProperties.ServiceName = loggerProperties.AppCode;

            var provider = new SparkLogProvider(logStore, httpContextAccessor, loggerProperties);
            factory.AddProvider(provider);

            return app;
        }
    }
}